#include "Config.h"
#include <fstream>
#include <json/json.h>
#include "execmd.h"

int restore_json_file(const char* json_file_name) {
    std::string cpp_file_name = json_file_name;
    std::string fnbk_name = cpp_file_name + "_fnbk";
    std::string cmd = "cp " + fnbk_name + " " + cpp_file_name;

    static char a[16];
    memset(a, 0, 16);
    executeCMD(cmd.c_str(), a, 16);
    return 0;
}

Config::Config() {

}

Config::~Config() {
    
}

Config* Config::getInstance() {
    static Config config;
    return &config;
}

void Config::init(const std::string configPath) {
    std::ifstream in(configPath, std::ios::binary);
    if (!in.is_open()) {
        fprintf(stderr, "can't find %s. restore\n", configPath.c_str());
        restore_json_file(configPath.c_str());
        return;
    }
    Json::Reader reader;
    Json::Value root;
    if(!reader.parse(in, root)) {
        in.close();
        fprintf(stderr, "parse %s failed. restore.\n", configPath.c_str());
        //face
        restore_json_file(configPath.c_str());
        return;
    }

    if(!root.isMember("dataPath") || !root["dataPath"].isString()) {
        algoModelPath = DEFAULT_DATAPATH;
    }else {
        algoModelPath = root["dataPath"].asString();
    }

    if(!root.isMember("InImgWidth") || !root["InImgWidth"].isUInt() || 0 == root["InImgWidth"].asUInt()) {
        InWidth = DEFAULT_IMGWIDTH;
    }else {
        InWidth = root["InImgWidth"].asUInt();
    }

    if(!root.isMember("InImgHeight") || !root["InImgHeight"].isUInt() || 0 == root["InImgHeight"].asUInt()) {
        InHeight = DEFAULT_IMGHEIGHT;
    }else {
        InHeight = root["InImgHeight"].asUInt();
    }

    if(!root.isMember("OutImgWidth") || !root["OutImgWidth"].isUInt() || 0 == root["OutImgWidth"].asUInt()) {
        OutWidth = DEFAULT_IMGWIDTH;
    }else {
        OutWidth = root["OutImgWidth"].asUInt();
    }

    if(!root.isMember("OutImgHeight") || !root["OutImgHeight"].isUInt() || 0 == root["OutImgHeight"].asUInt()) {
        OutHeight = DEFAULT_IMGHEIGHT;
    }else {
        OutHeight = root["OutImgHeight"].asUInt();
    }

    if(!root.isMember("Rotation") || !root["Rotation"].isUInt()) {
        Rotation = 0;
    }else {
        Rotation = root["Rotation"].asUInt();
    }

    if(!root.isMember("enablePassportSideReg") || !root["enablePassportSideReg"].isBool()) {
        enablePassportSideReg = true;
    }else {
        enablePassportSideReg = root["enablePassportSideReg"].asBool();
    }

    if(!root.isMember("enablePassportCoverReg") || !root["enablePassportCoverReg"].isBool()) {
        enablePassportCoverReg = false;
    }else {
        enablePassportCoverReg = root["enablePassportCoverReg"].asBool();
    }

    if(!root.isMember("hostAddress") || !root["hostAddress"].isString()) {
        hostAddress = "http://192.168.21.19:52/login";
    }else {
        hostAddress = root["hostAddress"].asString();
    }
    in.close();
}